package com.study.interecptor.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.study.Util.HttpHelper;
import com.study.common.constants.RedisCache;
import com.study.annotation.RepeatSubmit;
import com.study.common.RepeatSubmitModel;
import com.study.common.constants.BaseConstants;
import com.study.interecptor.RepeatSubmitInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 重复验证
 *
 * @Author hupengming
 * @ClassName SameUrlDataInterceptor
 * @Date 2022-11-11 10:53
 * @Version 1.0
 */
@Slf4j
@Component
public class SameUrlDataInterceptor extends RepeatSubmitInterceptor {

    @Autowired
    RedisCache redisCache;

    @Override
    public boolean isRepeatSubmit(HttpServletRequest request, RepeatSubmit repeatSubmit) {
        // 获取请求头参数
        String nowParams = HttpHelper.getBodyString(request);
        log.info("nowParams 【1】--==>{}",nowParams);

        // 获取parameter参数
        if (StringUtils.isEmpty(nowParams)) {
            nowParams = JSON.toJSONString(request.getParameterMap());
            log.info("nowParams 【2】--==>{}",nowParams);
        }
        // 构建Map
        RepeatSubmitModel nowDataMap = new RepeatSubmitModel();
        nowDataMap.setRepeatParams(nowParams);
        nowDataMap.setRepeatTime(System.currentTimeMillis());

        String URI = request.getRequestURI();
        String ticket = StringUtils.trimToEmpty(request.getHeader(BaseConstants.TOKEN));
        String key = URI + ticket;
        log.info("key --==>{}",key);

        String object = redisCache.getRepeatSubmit(key);
        log.info("object --==>{}",object);
        if(object != null){
            JSONObject jsonObject = JSON.parseObject(object);
            if(ObjectUtil.isNotNull(jsonObject)){
                Object val = jsonObject.get(URI);
                log.info("val --==> {}",val);
                if(val != null){
                    String format = String.format("%s",val);
                    RepeatSubmitModel preDataMap = JSON.parseObject(format, RepeatSubmitModel.class);
                    if(StringUtils.equals(nowDataMap.getRepeatParams(),preDataMap.getRepeatParams())
                            && (nowDataMap.getRepeatTime() - preDataMap.getRepeatTime()) < repeatSubmit.interval()){
                        return true;
                    }
                }
            }
        }

        Map<String,Object> data = new HashMap<>();
        data.put(URI,nowDataMap);
        redisCache.setRepeatSubmit(key,JSON.toJSONString(data),repeatSubmit.interval());
        return false;
    }

}
